package com.ruoyi.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.PageUtils;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

import static cn.hutool.poi.excel.sax.AttributeName.t;

@ClientEndpoint
public class WebSocketClientEndpoint {

    private Session userSession = null;
    private MessageHandler messageHandler;
    public String msg=null;
    public String error=null;
    private int retryCount = 0;

    public WebSocketClientEndpoint(String endpointURI) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, URI.create(endpointURI));
        } catch (Exception e) {
            this.error = "刷卡设备连接失败";

//            throw new RuntimeException(e);
        }
    }

    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;




    }

    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
//        retryConnect();
    }

    public void Close(){
        try {
            this.userSession.close();
        }catch (Exception e) {
            System.out.println("Error Close: " + e.getMessage());
        }
    }

    @OnMessage
    public void onMessage(String message) {
        this.msg = message;

        if (this.messageHandler != null) {
//            this.messageHandler.handleMessage(message);


        }
    }

//    @OnOpenException
//    public void onOpenException(Exception ex) {
//        System.out.println("Error opening websocket: " + ex.getMessage());
//        retryConnect();
//    }

    private void retryConnect() {
        if (retryCount < 5) {
            try {
                Thread.sleep(1000); // 等待1秒后重试连接
                WebSocketContainer container = ContainerProvider.getWebSocketContainer();
                container.connectToServer(this, URI.create("ws://localhost:7415/"));
                retryCount++;
            } catch (Exception e) {
                System.out.println("Error reconnecting: " + e.getMessage());
                retryConnect(); // 如果连接失败，继续重试连接
            }
        } else {
            System.out.println("Max retries reached, giving up.");
        }
    }

    public void sendMessage(String message) throws IOException {
        System.out.printf("ws连接"+String.valueOf(this.userSession.isOpen()));
        this.userSession.setMaxTextMessageBufferSize(999999999);
        this.userSession.setMaxIdleTimeout(99999999);
        this.userSession.getBasicRemote().sendText(message);
    }

    public void addMessageHandler(MessageHandler handler) {
        this.messageHandler = handler;
    }
}